package com.gorkr.cronback.pattern.designPattern.observer;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 发布cronString 到解析服务
 */
public class CronStringPublisher implements CronStringSubject{
    private List<CronObserver> cronObservers = new ArrayList<>();
    private String cronString;

    @Override
    public void registerCronObserver(CronObserver cronObserver) {
        cronObservers.add(cronObserver);

    }

    @Override
    public void removeCronObserver(CronObserver cronObserver) {
        int index = cronObservers.indexOf(cronObserver);
        if(index>=0){
            cronObservers.remove(index);
        }


    }

    @Override
    public Map<String, Object> notifyCronObserver() throws Exception {
        HashMap<String, Object> res = new HashMap<>();

        // 调用订阅者的update方法
        for (CronObserver cronObserver: cronObservers ){
            String[] s = cronObserver.getClass().getName().split("\\.");
            res.put(s[s.length-1],cronObserver.update(cronString));
        }
        return res;

    }

    public Map<String, Object> setCronString(String cronString) throws Exception {
        this.cronString = cronString;
        return notifyCronObserver();
    }
}
